/*
	业务运行时序图
*/
define(
	[
		'require',
		'echarts',
		'echarts/config',
		'echarts/chart/bar',
		'zrender/config',
		'zrender/tool/event',
		'zrender/tool/util'
	],
	function (require) {
		"use strict";

		var echarts = require('echarts');
		var ecConfig = require('echarts/config');
		var zrConfig = require('zrender/config');
		var zrEvent = require('zrender/tool/event');
		var zrUtil = require('zrender/tool/util');

		var forEach = Ember.EnumerableUtils.forEach;
		var map = Ember.EnumerableUtils.map;

		var defaultOption = {
			grid: {
				x: 0,
				y: 0,
				x2: 0,
				y2: 0,
				borderWidth: 0
			},
			tooltip : {
				trigger: 'axis',
				formatter: "{b} &nbsp; "+(overviewOrCenterSwitch == "system"?"吞吐量":"交易量")+": {c}",
				showDelay: 0,
				transitionDuration: 0,
				position: function(pos){
					return [pos[0], 10];
				}
			},
			xAxis : [
				{
					type : 'category',
					axisLine: {
						show: false
					},
					axisLabel: {
						show: false,
						//标签的间隔决定了分割线的间隔
						interval: 0,
						textStyle: {
							align: "left"
						}
					},
					axisTick: {
						show: false,
						interval: 3
					},
					splitLine : {
						show: true,
						lineStyle: {
							color: "rgba(0,0,0,0.1)",
							type: 'solid',
							width: 1
						}
					},
					splitArea : {
						show: true,
						areaStyle:{
							color:['rgba(92,203,57,0.3)','rgba(92,203,57,0.3)']
						}
					},
					data : null
				}
			],
			yAxis : [
				{
					type : 'value',
					axisLine: {
						show: false
					},
					axisLabel: {
						show: false
					},
					splitLine : {
						show:false
					}
				}
			],
			series : [
				{
					type:'bar',
					data: ['-'],
					name: overviewOrCenterSwitch == "system"?"吞吐量":"交易量",
					barCategoryGap: 2,
					itemStyle: {
						normal: {
							color: 'rgba(92,203,57,1)'
						}
					}
				}
			]
		};

		var SequenceView = Ember.Component.extend({
			dataKey: "system/throughput/total",

			displayMode: "detail",

			init: function(){
				this._super();
				this.dataChange();
			},

			didInsertElement: function(){
				var view = this;
				var $dom = this.$().css("position", "relative");

				this.width = $dom.width();
				this.height = $dom.height();

				if(this.width === 0 || this.height === 0){
					Ember.assert("必须指定视图的width和height。（可通过样式或width，height属性");
					return;
				}

				this._overviewView = jQuery("<div></div>").appendTo($dom);
				this._manifierView = jQuery("<div></div>").appendTo($dom).hide();

				this._initNormalChart();
				this._initManifierChart();

				APM.on("mainContainerResize", this, "_resizeChart");
				$(window).on("resize."+this.elementId, function(){
					
					view._resizeChart();
				});
			},

			willDestroyElement: function(){
				this.overviewChart.dispose();
				this.manifierChart.dispose();
				this.overviewChart = null;
				this.manifierChart = null;
				this._overviewView = null;
				this._manifierView = null;
				APM.off("mainContainerResize");
				$(window).off("resize."+this.elementId);
			},

			/**
			 * 初始化概览图表
			 */
			_initNormalChart: function(){
				var $dom = this.$();

				this._overviewView.css({
					width: $dom.width(),
					height: $dom.height()
				});

				if(G_vmlCanvasManager && G_vmlCanvasManager.init){
					G_vmlCanvasManager.initElement(this._overviewView[0]);
				}

				var overviewChart = echarts.init(this._overviewView[0]);

				this.overviewChart = overviewChart;

				this._overviewView.find(">div").css("overflow", "visible");

				this.dataChange();

				this._addListenerNormalChart();
			},

			/**
			 * 初始化放大镜图表
			 */
			_initManifierChart: function(){
				this._manifierView.css({
					width: 50,
					height: 30,
					borderRadius: 25,
					border: "#619bc9 1px solid",
					overflow: "hidden",
					position: "absolute",
					zIndex: "10"
				});

				if(G_vmlCanvasManager && G_vmlCanvasManager.init){
					G_vmlCanvasManager.initElement(this._manifierView[0]);
				}

				var manifierChart = echarts.init(this._manifierView[0]);

				this.manifierChart = manifierChart;

				this._manifierView.css("height", 50);
				this._manifierView.find(">div").css({
					top: 9
				});

				this.magnifyDataChange();

				this._addListenerManifierChart();
			},

			/**
			 * 绑定概览图表的事件
			 */
			_addListenerNormalChart: function(){
				var overviewChartZr = this.overviewChart._zr,
					zrConfigEvent = zrConfig.EVENT,
					ecConfigEvent = ecConfig.EVENT,
					runBind = Ember.run.bind;

				overviewChartZr.on(zrConfigEvent.MOUSEMOVE, runBind(this, "_overviewOnMousemove"));
				overviewChartZr.on(zrConfigEvent.GLOBALOUT, runBind(this, "_zrOnGlobalout"));
				overviewChartZr.on(ecConfigEvent.CLICK, runBind(this, "_overviewOnItemClick"));
			},

			/**
			 * 绑定放大镜图表的事件
			 */
			_addListenerManifierChart: function(){
				var manifierChartZr = this.manifierChart._zr,
					zrConfigEvent = zrConfig.EVENT,
					ecConfigEvent = ecConfig.EVENT,
					runBind = Ember.run.bind;

				manifierChartZr.on(zrConfigEvent.MOUSEMOVE, runBind(this, "_manifierOnMousemove"));
				manifierChartZr.on(zrConfigEvent.GLOBALOUT, runBind(this, "_zrOnGlobalout"));
				manifierChartZr.on(ecConfigEvent.CLICK, runBind(this, "_overviewOnItemClick"));
				this.manifierChart.on(ecConfigEvent.TOOLTIP_HOVER, runBind(this, "_manifierOnTooltipHover"));
			},

			/**
			 * 概览图表事件响应：数据项点击
			 */
			_overviewOnItemClick: function(args){
				this.sendAction("itemClick", this.curHoverData, this);
			},

			/**
			 * 概览图表事件响应：鼠标在绘图区域移动
			 */
			_overviewOnMousemove: function (param) {
				var view = this;
				this._findHoverData(param);

				this.sendAction("overviewMousemove", this.curHoverData, this);

				clearTimeout(this._showingTimer);
				clearTimeout(this._hidingTimer);

				this._showingTimer = setTimeout(function(){
					if(view.displayMode == "overview"){
						view._showMagnifier(param);
					}
				});
			},

			/**
			 * 放大镜图表事件响应：鼠标在绘图区域移动
			 */
			_manifierOnMousemove: function(param){
				clearTimeout(this._showingTimer);
				clearTimeout(this._hidingTimer);
				this._manifierView.show();
			},

			/**
			 * 放大镜图表事件响应：取消自己的tooltip显示, 启用概览视图的tooltip显示
			 */
			_manifierOnTooltipHover: function(args){
				var magnifyData = this.get("magnifyData")||[];
				this.overviewChart.component.tooltip._showAxisTrigger(0, 0, this.curMagnifyDataIndex + args.dataIndex - 2);

				this.curHoverData = magnifyData[args.dataIndex];
			},

			/**
			 * zrender事件响应：鼠标离开绘图区域
			 */
			_zrOnGlobalout: function () {
				var ctrl = this;
				clearTimeout(this._showingTimer);
				clearTimeout(this._hidingTimer);
				this._hidingTimer = setTimeout(function(){
					ctrl._hideMagnifier();
				}, 100);

				this.sendAction("mouseoutChart", this);

				var tooltip = (this.overviewChart && this.overviewChart.component && this.overviewChart.component.tooltip);
				if(tooltip){
					//解决鼠标在放大镜图表往下移除时, 概览tooltip没隐藏的问题
					tooltip.__onglobalout();
					//模拟联动TOOLTIP_OUT_GRID事件, 解决联动图标tooltip没隐藏的问题
					var connected = this.overviewChart._connected;
					for (var c in connected) {
						connected[c].connectedEventHandler({
							__echartsId: this.overviewChart.id,
							event: tooltip._event,
							type: ecConfig.EVENT.TOOLTIP_OUT_GRID,
							x: 1.1,
							y: 1.1
						});
					}
				}
			},

			_findHoverData: function(param){
				var data = this.get("data")||[],
					xAxis = this.overviewChart.component.xAxis,
					target = param.target,
					dataIndex,
					oldHoverData = this.curHoverData,
					oldHoverDataIndex = this.curMagnifyDataIndex;

				if(!xAxis){
					return;
				}

				dataIndex = this._getNearestDataIndex(param.event, xAxis.getAxis(0));
				
				if(dataIndex == -1){
					this.curHoverData = null;
					this.curMagnifyDataIndex = -1;
				}else{
					this.curHoverData = data[dataIndex];
					this.curMagnifyDataIndex = dataIndex;
				}
			},

			/**
			 * 显示放大镜
			 */
			_showMagnifier: function(param){
				var data = this.get("data")||[];
				var dataLen = data.length;
				var dataIndex = this.curMagnifyDataIndex;

				if(dataIndex == -1){
					return;
				}

				var startIndex = Math.max(0, dataIndex-2);
				var endIndex = Math.min(dataLen, dataIndex+2);
				if(startIndex == 0){
					endIndex = Math.max(endIndex, Math.min(dataLen, 4));
				}
				if(endIndex == dataLen){
					startIndex = Math.min(startIndex, Math.max(0, dataIndex-4));
				}

				this.set("magnifyData", data.slice(startIndex, endIndex+1));

				var x = zrEvent.getX(param.event);
				var y = zrEvent.getY(param.event);
				this._manifierView.css({
					left: x - 25,
					top: 30
				})
				.show();
			},

			/**
			 * 隐藏放大镜
			 */
			_hideMagnifier: function(){
				this._manifierView&&this._manifierView.hide();
			},

			/**
			 * 根据坐标轴事件带的属性获取最近的axisDataIndex
			 */
			_getNearestDataIndex: function (e, categoryAxis) {
				var dataIndex = -1;
				var x = zrEvent.getX(e);
				var y = zrEvent.getY(e);
				var left;
				var right;
				var xEnd = this.overviewChart.component.grid.getXend();
				var curCoord = categoryAxis.getCoordByIndex(dataIndex);
				while (curCoord < xEnd) {
					right = curCoord;
					if (curCoord <= x) {
						left = curCoord;
					}
					else {
						break;
					}
					curCoord = categoryAxis.getCoordByIndex(++dataIndex);
				}
				if (dataIndex <= 0) {
					dataIndex = 0;
				}
				else if (x - left <= right - x) {
					dataIndex -= 1;
				}
				else {
					// 离右边近，看是否为最后一个
					if (categoryAxis.getNameByIndex(dataIndex) == null) {
						dataIndex -= 1;
					}
				}
				return dataIndex;
			},

			/**
			 * 数据改变后, 根据显示模式设置为相应的数据
			 */
			dataChange: Ember.observer("data", function(){
				switch(this.displayMode){
					case "overview":
						this.overviewDataChange();
						break;
					case "detail":
						this.detailDataChange();
						break;
				}
			}),

			/**
			 * 概览数据改变后, 刷新概览图表
			 */
			overviewDataChange: function(){
				if(!this.overviewChart){
					return;
				}

				var option = zrUtil.clone(defaultOption);
				if(overviewOrCenterSwitch == "system"){
					option.tooltip.formatter = "{b} &nbsp; 吞吐量: {c}";
				}else{
					option.tooltip.formatter = "{b} &nbsp; 交易量: {c}";
				}
				var data = this.get("data")||[];
				var xAxisData = option.xAxis[0].data = [];
				var seriesData = option.series[0].data = [];
				var splitAreaColors = option.xAxis[0].splitArea.areaStyle.color = [];
				option.xAxis[0].splitLine.show = false;

				this._translateDataToOption(data, xAxisData, seriesData, splitAreaColors);

				this.overviewChart.setOption(option, true);
				this.overviewChart.hideLoading();
			},

			/**
			 * 详细数据改变后, 刷新概览图表
			 */
			detailDataChange: function(){
				var overviewChart = this.overviewChart;
				if(!overviewChart){
					return;
				}


				var option = zrUtil.clone(defaultOption);
				if(overviewOrCenterSwitch == "system"){
					option.tooltip.formatter = "{b} &nbsp; 吞吐量: {c}";
				}else{
					option.tooltip.formatter = "{b} &nbsp; 交易量: {c}";
				}
				
				var data = this.get("data")||[];
				var xAxisData = option.xAxis[0].data = [];
				var seriesData = option.series[0].data = [];

				var splitAreaColors = option.xAxis[0].splitArea.areaStyle.color = [];

				this._translateDataToOption(data, xAxisData, seriesData, splitAreaColors);


				overviewChart.setOption(option, true);
				overviewChart.hideLoading();

				this._hideMagnifier();

				// if(overviewChart.component.tooltip){
				// 	overviewChart._zr.un(zrConfig.EVENT.GLOBALOUT, overviewChart.component.tooltip._onglobalout);
				// }
			},

			/**
			 * 放大镜数据改变后, 刷新放大镜图表
			 */
			magnifyDataChange: Ember.observer("magnifyData", function(){
				var manifierChart = this.manifierChart;
				var magnifyData = this.get("magnifyData")||[];
				if(!manifierChart || magnifyData.length == 0){
					return;
				}

				var option = zrUtil.clone(defaultOption);
				var xAxisData = option.xAxis[0].data = [];
				var seriesData = option.series[0].data = [];
				var splitAreaColors = option.xAxis[0].splitArea.areaStyle.color = [];
				option.backgroundColor = "#225187";
				option.borderColor = "#17365a";
				option.tooltip.showContent = false;

				this._translateDataToOption(magnifyData, xAxisData, seriesData, splitAreaColors);

				manifierChart.setOption(option, true);
				manifierChart.hideLoading();
			}),

			/**
			 * 将原始值转换为柱形图需要的series配置
			 */
			_translateSeriesDataItem: function(performance){
				var dataKey = this.get("dataKey");
				if(overviewOrCenterSwitch == "business"){
					dataKey = "business/throughput/total";
				};
		
				var value = performance[dataKey],
					valueItem = {
						value: value === undefined ? "-" : value,
						origData: performance
					};

				if(overviewOrCenterSwitch == "business"){
					var statusColor = performance.businessStatus;
				}else{
					var statusColor = performance.status;
				}	

				switch(statusColor){
					case 1:
						valueItem.itemStyle = {
							normal: {
								color: 'rgba(235,228,28,1)'
							}
						}
						break;
					case 2:
						valueItem.itemStyle = {
							normal: {
								color: 'rgba(255,94,63,1)'
							}
						}
						break;
					case 0:
						valueItem.itemStyle = {
							normal: {
								color: 'rgba(138,237,119,1)'
							}
						}
						break;
					default:
						break;
				}
				return valueItem;
			},

			/**
			 * 将原始值转换为柱形图的xAxis配置
			 */
			_translateXAxisDataItem: function(performance){
				var xAxisData;
				switch(this.displayMode){
					case "overview":
						var date = new Date(performance.timestamp);
						xAxisData = (date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":00";
						break;
					case "detail":
						xAxisData = (new Date(performance.timestamp)).toTimeString().substr(0, 5);
						break;
					default:
						xAxisData = "-";
						break;
				}
				return xAxisData;
			},

			/**
			 * 根据数据生成SplitAreaColor配置
			 */
			_translateSplitAreaColor: function(performance){
				var dataKey = this.get("dataKey");
				var value = performance[dataKey],
					color;

				if(overviewOrCenterSwitch == "business"){
					var statusColor = performance.businessStatus;
				}else{
					var statusColor = performance.status;
				}	
				switch(statusColor){
					case 1:
						color = 'rgba(235,228,28,0.15)';
						break;
					case 2:
						color = 'rgba(255,94,63,0.15)';
						break;
					case 0:
						color = 'rgba(138,237,119,0.15)';
						break;
					default:
						color = 'rgba(0,0,0,.15)';
						break;
				}
				return color;
			},

			/**
			 * 将原始值转换为柱形图的配置
			 */
			_translateDataToOption: function(data, xAxisData, seriesData, splitAreaColors){
				var view = this;
				forEach(data, function(performance){
					xAxisData.push(view._translateXAxisDataItem(performance));
					seriesData.push(view._translateSeriesDataItem(performance));
					splitAreaColors && splitAreaColors.push(view._translateSplitAreaColor(performance))
				});
				if(xAxisData.length == 0){
					xAxisData.push("-");
				}
			},

			/**
			 * 添加新的时间点性能数据, 用于实时模式中实时添加最新性能
			 */
			addTimePoints: function(performances){
				var view = this;
				var data = this.get("data");
				Ember.A(performances);

				forEach(performances, function(performance){
					var valueItem = view._translateSeriesDataItem(performance);

					view.overviewChart.addData([
						[
							0,		// 系列索引
							valueItem, // 新增数据
							false,	// 新增数据是否从队列头部插入
							false,	// 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
							view._translateXAxisDataItem(performance)  // 坐标轴标签
						]
					]);
				});
			},

			/**
			 * 显示加载中动画, 图表初始化后才能使用
			 */
			showLoading: function(){
				this.overviewChart.showLoading();
			},

			/**
			 * 隐藏加载中动画, 图表初始化后才能使用
			 */
			hideLoading: function(){
				this.overviewChart.hideLoading();
			},

			_resizeChart: function(){
				var $dom = this.$();
				this.width = $dom.width();
				this.height = $dom.height();

				this._overviewView.css({
					width: this.width,
					height: this.height
				});

				this.overviewChart.resize();
			}
		});

		return SequenceView;
	}
);